package article

import (
	"time"

	"gorm.io/gorm"

	"BookStack/pkg/errors"
	"BookStack/pkg/utils"
)

// 文章状态常量
const (
	StatusDraft     uint = 0 // 草稿
	StatusPublished uint = 1 // 已发布
	StatusArchived  uint = 2 // 已归档
)

// Article 文章实体
type Article struct {
	ID          uint      `json:"id"`
	Title       string    `json:"title"`
	Slug        string    `json:"slug"`
	Summary     string    `json:"summary"`
	Content     string    `json:"content"`
	CategoryID  uint      `json:"category_id"`
	AuthorID    uint      `json:"author_id"`
	CoverImage  string    `json:"cover_image"`
	Views       uint      `json:"views"`
	Likes       uint      `json:"likes"`
	Comments    uint      `json:"comments"`
	Status      uint      `json:"status"`
	IsRecommend bool      `json:"is_recommend"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	PublishedAt time.Time `json:"published_at" gorm:"default:null"`
	DeletedAt   gorm.DeletedAt
}

// TableName 指定表名
func (Article) TableName() string {
	return "articles"
}

// NewArticle 创建一个新的文章实体
func NewArticle(title, content, summary string, authorID, categoryID uint, coverImage string, customSlug string) (*Article, error) {
	if title == "" {
		return nil, errors.New(errors.ErrCodeArticleTitleRequired, "")
	}
	if content == "" {
		return nil, errors.New(errors.ErrCodeArticleContentRequired, "")
	}

	now := time.Now()

	// 使用自定义slug或生成新的
	slug := customSlug
	if slug == "" {
		slug = generateSlug(title)
	}

	return &Article{
		Title:       title,
		Slug:        slug,
		Summary:     summary,
		Content:     content,
		CategoryID:  categoryID,
		AuthorID:    authorID,
		CoverImage:  coverImage,
		Status:      StatusDraft,
		IsRecommend: false,
		CreatedAt:   now,
		UpdatedAt:   now,
		// 不设置PublishedAt，保持为空值，让GORM自动转换为NULL
	}, nil
}

// Update 更新文章
func (a *Article) Update(title, content, summary string, categoryID uint, coverImage string) error {
	if title == "" {
		return errors.New(errors.ErrCodeArticleTitleRequired, "")
	}
	if content == "" {
		return errors.New(errors.ErrCodeArticleContentRequired, "")
	}
	// if categoryID == 0 {
	// 	return errors.New(errors.ErrCodeArticleCategoryRequired, "")
	// }

	// 如果标题变更，需要重新生成slug
	if a.Title != title {
		a.Slug = generateSlug(title)
	}

	a.Title = title
	a.Content = content
	a.Summary = summary
	a.CategoryID = categoryID
	a.CoverImage = coverImage
	a.UpdatedAt = time.Now()
	return nil
}

// Publish 发布文章
func (a *Article) Publish() error {
	if a.Status == StatusPublished {
		return nil
	}
	a.Status = StatusPublished
	a.PublishedAt = time.Now()
	a.UpdatedAt = time.Now()
	return nil
}

// Archive 归档文章
func (a *Article) Archive() error {
	if a.Status == StatusArchived {
		return nil
	}
	a.Status = StatusArchived
	a.UpdatedAt = time.Now()
	return nil
}

// Draft 设置为草稿
func (a *Article) Draft() error {
	if a.Status == StatusDraft {
		return nil
	}
	a.Status = StatusDraft
	a.UpdatedAt = time.Now()
	return nil
}

// SetStatus 设置文章状态
func (a *Article) SetStatus(status uint) error {
	if status > StatusArchived {
		return errors.New(errors.ErrCodeArticleStatusInvalid, "").WithDetails(map[string]interface{}{
			"status": status,
		})
	}
	if a.Status == status {
		return nil
	}

	a.Status = status
	a.UpdatedAt = time.Now()

	// 如果是发布状态，设置发布时间
	if status == StatusPublished && a.PublishedAt.IsZero() {
		a.PublishedAt = time.Now()
	}

	return nil
}

// SetRecommend 设置推荐状态
func (a *Article) SetRecommend(isRecommend bool) {
	if a.IsRecommend == isRecommend {
		return
	}
	a.IsRecommend = isRecommend
	a.UpdatedAt = time.Now()
}

// IncrementViews 增加浏览次数
func (a *Article) IncrementViews() {
	a.Views++
	a.UpdatedAt = time.Now()
}

// IncrementLikes 增加点赞数
func (a *Article) IncrementLikes() {
	a.Likes++
	a.UpdatedAt = time.Now()
}

// DecrementLikes 减少点赞数
func (a *Article) DecrementLikes() {
	if a.Likes > 0 {
		a.Likes--
		a.UpdatedAt = time.Now()
	}
}

// IncrementComments 增加评论数
func (a *Article) IncrementComments() {
	a.Comments++
	a.UpdatedAt = time.Now()
}

// DecrementComments 减少评论数
func (a *Article) DecrementComments() {
	if a.Comments > 0 {
		a.Comments--
		a.UpdatedAt = time.Now()
	}
}

// IsPublished 判断是否已发布
func (a *Article) IsPublished() bool {
	return a.Status == StatusPublished
}

// IsDraft 判断是否为草稿
func (a *Article) IsDraft() bool {
	return a.Status == StatusDraft
}

// IsArchived 判断是否已归档
func (a *Article) IsArchived() bool {
	return a.Status == StatusArchived
}

// generateSlug 生成文章slug
func generateSlug(title string) string {
	// 基础slug
	baseSlug := utils.Slugify(title)

	// 如果slug为空，使用当前时间戳
	if baseSlug == "" {
		return utils.Slugify(time.Now().Format("20060102-150405"))
	}

	// 为确保唯一性，添加短的随机字符串
	// 格式: base-slug-[6位随机字符]
	randomStr := utils.RandomString(6)
	return baseSlug + "-" + randomStr
}
